package liuyuyang.filter;

import liuyuyang.config.FilterProperties;
import liuyuyang.utils.Jwt;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import liuyuyang.domain.User;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
@EnableConfigurationProperties({FilterProperties.class})
public class LoginFilter implements GlobalFilter, Ordered {
    @Resource
    private FilterProperties filterProperties;
    @Resource
    private Jwt jwt;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获得请求的路径
        System.out.println(exchange.getRequest().getURI());
        // http://localhost:10010/user-service/user/verify

        String path = exchange.getRequest().getURI().getPath();
        // /user-service/user/verify

        System.out.println(path);

        // 白名单列表
        List<String> allowPathList = filterProperties.getAllowPaths();

        // 如果请求的路径在白名单中就放行，允许访问
        for (String allow : allowPathList) {
            if (path.contains(allow)) {
                return chain.filter(exchange);
            }
        }

        // 校验Token && 获取Token
        String Token = exchange.getRequest().getHeaders().getFirst("Authorization");

        User data = new User();
        data.setUsername("jack");
        data.setPassword("123123");

        try {
            // 解析Token
            User user = jwt.resolverToken(Token, User.class);
            System.out.println(user);

            // 如果解析成功就放行
            return chain.filter(exchange);
        } catch (Exception e) {
            System.out.println(e);
            // 处理失败结果
            ServerHttpResponse response = exchange.getResponse();

            // 设置状态码为401 表示没有权限
            response.setStatusCode(HttpStatus.UNAUTHORIZED);        // 401
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            DataBuffer wrap = response.bufferFactory().wrap("没有权限".getBytes(StandardCharsets.UTF_8));

            // 将指定内容写入到网页
            return exchange.getResponse().writeWith(Flux.just(wrap));
        }
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
